//
//  HMOAuthViewController.swift
//  CZBKWB31
//
//  Created by Linkon Y on 16/8/10.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        
        //       let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBAppSecret)")!
        
        //判断URL是否为nil
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)") else{
            return
     }
        //设施代理
        webView.delegate = self
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: - 监听方法
    //取消
    @objc private func cancelAction(){
        dismissViewControllerAnimated( true, completion: nil)
    }
    //自动填充
    @objc private func autofillClick(){
        
        //账号登录-----------------------------------------------------------------------
        let jsString = "document.getElementById('userId').value='88fishyu@163.com',document.getElementById('passwd').value='123465789'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    // MARK: - 设置UI
    private  func setupUI(){
        view.backgroundColor =  UIColor.whiteColor()
        setupNav()
    }
    
    // MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", style: UIBarButtonItemStyle.Plain, target: self, action: "autofillClick")
        navigationItem.title = "微博登录"
    }
    
    // MARK: - 懒加载控件
    private lazy var webView : UIWebView = UIWebView()
}

extension HMOAuthViewController : UIWebViewDelegate {
    // 监听webView将要加载的request
    //  默认返回true
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //记载urlstring
        //判断url是否为nil   他的前缀是否为我们的设置的回调页
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_uri){
            //qrury请求参数
            //nil的判断
            if let equry = request.URL?.query{
                let code = equry.substringFromIndex("code=".endIndex)
//                print("用户code:\(code)")
                HMUserAccountViewModel.sharedTools.getUserAccount(code, finish: { (isSuccess) in
                    if !isSuccess {
                        print("请求失败")
                        return
                    }
                    print("请求成功")
                    self.dismissViewControllerAnimated(false, completion: {
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSWITCHROOTVCNOTIFICATION, object: "oauth")
                    })
                })
                
                return false
            }
        }
        return true
    }
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
    }
}

// MARK: - 请求数据
extension HMOAuthViewController{
    //以下方法已经抽取78行
    //    //获取授权
    //    func getUserAccunt(code: String){
    //
    //        HMNetworkTool.sharedTools.oauthLoadUserAccount(code, success: { (response) in
    //            //请求成功
    //            //print("请求成功\(response)")
    //            guard let res = response as? [String : AnyObject] else{
    //                return
    //            }
    //            //通过字典创建模型
    //            let  userAccount = HMUserAccount_Model(dict:res)
    //            //不会形成循环
    //            self.getUserInfo(userAccount)
    //        }) { (error) in
    //            //请求失败
    //            print("请求失败\(error)")
    //        }
    //    }
    //
    //    //请求个人信息
    //    func getUserInfo(userAccount:HMUserAccount_Model){
    //
    //        HMNetworkTool.sharedTools.oauthLoadUserInfo(userAccount, success: { (response) in
    //            //判断是否为nil 是否可以转为字典
    //            guard let res = response  as? [String:AnyObject] else{
    //                return
    //            }
    //            //赋值
    //            userAccount.screen_name = res["screen_name"] as? String
    //            userAccount.avatar_large = res["avatar_large"] as? String
    //            print(userAccount)
    //        }) { (error) in
    //            print("请求失败\(error)")
    //            
    //        }
    //    }
}

